package com.top.horizon.th1804app.view;

import android.app.Dialog;
import android.content.Context;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;

import com.top.horizon.th1804app.utils.RangeUtil;

public class CustomDialog extends Dialog {
    private OnClickChildVIewListener mOnClickChildVIewListener;
    private View inflate;
    private int mLayoutId;
    private Context mContext;

    public CustomDialog(@NonNull Context context) {
        this(context, 0);
    }

    public CustomDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题
        this.mContext = context;
        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题
    }

    public CustomDialog(@NonNull Context context, int themeResId, int layoutId) {
        super(context, themeResId);
        inflate = View.inflate(context, layoutId, null);
        mLayoutId = layoutId;

    }

    public void setLayout(int layoutId){
        inflate = View.inflate(mContext, layoutId, null);
        this.mLayoutId = layoutId;
    }

    public void showDialog() {
        if (mOnClickChildVIewListener != null)
            mOnClickChildVIewListener.onClickChildView(inflate, mLayoutId);
        addContentView(inflate, new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        setContentView(inflate);
        Window dialogWindow = this.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = RangeUtil.dip2px(mContext,560);
        lp.height = RangeUtil.dip2px(mContext,365);
        dialogWindow.setAttributes(lp);
        show();

    }

    public void showDialog(View view){
        if (view.getParent() != null){
            ViewGroup parent = (ViewGroup) view.getParent();
            parent.removeView(view);
        }
        if (mOnClickChildVIewListener != null)
            mOnClickChildVIewListener.onClickChildView(view, mLayoutId);
        addContentView(view, new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        setContentView(view);
        Window dialogWindow = this.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = RangeUtil.dip2px(mContext,560);
        lp.height = RangeUtil.dip2px(mContext,365);
        dialogWindow.setAttributes(lp);
        show();
    }



    public void setOnClickChildVIewListener(OnClickChildVIewListener onClickChildVIewListener) {
        this.mOnClickChildVIewListener = onClickChildVIewListener;
    }

    public interface OnClickChildVIewListener {
        void onClickChildView(View view, int mLayoutId);
    }
}
